﻿/*********************************************
 创建者：  george
 创建时间：2016-10-31
 功能说明：系统角色管理
 ********************************************/
using BaseAPI.model;
using com.nm.ApiServer;
using com.nm.ApiServer.Attributes;
using com.nm.Attributes;
using com.nm.db.Models.Systems;
using com.nm.Helper;
using EntityFramework.Extensions;
using george.Data;
using Nancy.Extensions;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using com.nm;
using static BaseAPI.model.RoleData;

namespace BaseAPI
{
    [MustAdmin]
    [Description("系统角色管理")]
    public class RoleHandler : BaseHandler
    {
        [JsonType]
        [Description("创建角色")]
        [ReturnType(typeof(int), "0-成功")]
        public ApiResult Create([ParamDescription("输入参数")]model.RoleData.CreateData param)
        {
            var dc = new SysEntities();
            if (string.IsNullOrWhiteSpace(param.RoleName)) return Error("角色名称不能为空");
            if (!param.RoleType.IsBetween(0, 4)) return Error("无效的角色类型");
            if (dc.sys_role.Any(t => t.RoleName == param.RoleName)) return Error("角色名称已存在");
            if (param.RoleName.Length > 20) return Error("【角色名称】长度超出限制");
            if (!string.IsNullOrWhiteSpace(param.Memo) && param.Memo.Length > 100) return Error("【备注】长度超出限制");
            var add = new sys_role
            {
                RoleName = param.RoleName,
                RoleType = param.RoleType,
                Sort = param.Sort,
                IsEffective = param.IsEffective,
                Memo = param.Memo,
                IsRemove = false,
                DeptID = param.DeptID
            };
            dc.sys_role.Add(add);
            try
            {
                dc.SaveChanges();
            }
            catch (Exception ex)
            {
                return Error(ex.Message);
            }
            return Success(0);
        }

        [JsonType]
        [Description("编辑角色")]
        [ReturnType(typeof(int), "0-成功")]
        public ApiResult Modify([ParamDescription("输入参数")]model.RoleData.ModifyData param)
        {
            var dc = new SysEntities();
            if (string.IsNullOrWhiteSpace(param.RoleName)) return Error("角色名称不能为空");
            if (!param.RoleType.IsBetween(0, 4)) return Error("无效的角色类型");
            if (param.RoleName.Length > 20) return Error("【角色名称】长度超出限制");
            if (!string.IsNullOrWhiteSpace(param.Memo) && param.Memo.Length > 100) return Error("【备注】长度超出限制");
            var query = dc.sys_role.FirstOrDefault(t => t.ID == param.ID);
            if (query == null) return Error("无数据");
            query.IsEffective = param.IsEffective;
            query.Memo = param.Memo;
            query.RoleName = param.RoleName;
            query.RoleType = param.RoleType;
            query.Sort = param.Sort;
            query.DeptID = param.DeptID;
            try
            {
                dc.SaveChanges();
            }
            catch (Exception ex)
            {
                return Error(ex.Message);
            }
            Log.WriteLines("用户ID："+this.UserId+",时间："+DateTime.Now+",修改了角色分类!");
            return Success(0);
        }

        [Description("删除角色")]
        [ReturnType(typeof(int), "0-成功")]
        public ApiResult Remove([ParamDescription("角色ID")]int RoleID)
        {
            var dc = new SysEntities();
            if (dc.sys_module_privilege.Any(t => t.RoleID == RoleID)) return Error("角色已在使用中，无法删除");
            var user = (from u in dc.sys_v_userInfo
                        join ur in dc.sys_user_role on u.UserID equals ur.UserID
                        select new
                        {
                            u.IsRemove,
                            ur.RoleID,
                        }).FirstOrDefault(r => r.RoleID == RoleID && r.IsRemove == false);
            if (user != null) return Error("该岗位存在用户信息，无法删除！");
            var query = dc.sys_role.FirstOrDefault(t => t.ID == RoleID);
            if (query != null)
                query.IsRemove = true;
            try
            {
                dc.SaveChanges();
            }
            catch (Exception ex)
            {
                return Error(ex.Message);
            }
            return Success(0);
        }

        [Description("获取指定角色")]
        [ReturnType(typeof(model.RoleData.ModifyData))]
        public ApiResult GetID(int RoleID)
        {
            var dc = new SysEntities();
            var query = dc.sys_role.FirstOrDefault(t => t.IsRemove == false && t.ID==RoleID);
            if (query == null) return Error("无数据");
            var result = new model.RoleData.ModifyData
            {
                ID = query.ID,
                IsEffective = query.IsEffective,
                Memo = query.Memo,
                RoleName = query.RoleName,
                RoleType = query.RoleType,
                Sort = (int)query.Sort,
                DeptID = query.DeptID
            };
            return Success(result);
        }

        [Description("获取指定部门角色列表")]
        [ReturnType(typeof(PaperData<model.RoleData.ListData>))]
        public ApiResult GetList([ParamDescription("部门ID-预留")]int DeptID = 0,
            [ParamDescription("页码")]int Page = 1,
            [ParamDescription("页数")]int Size = 10)
        {
            var dc = new SysEntities();
            var query = (from r in dc.sys_role
                         where r.IsRemove == false && r.DeptID==DeptID
                         select new
                         {
                             r,
                             userCount = dc.sys_user_role.Count(t => t.RoleID == r.ID),
                             DeptName = dc.sys_dept.FirstOrDefault(t => t.DeptID == r.DeptID).DeptContent
                         });
            var result = PaperData<model.RoleData.ListData>.Create(query.Count(), Size, Page);
            result.Items = query.OrderBy(t => t.r.Sort).Skip(result.Skip).Take(result.Limt).Select(o => new model.RoleData.ListData
            {
                ID = o.r.ID,
                IsEffective = o.r.IsEffective,
                Memo = o.r.Memo,
                RoleName = o.r.RoleName,
                RoleType = o.r.RoleType,
                Sort = (int)o.r.Sort,
                UserCount = o.userCount,
                DeptName = o.DeptName
            }).ToList();
            return Success(result);
        }

        [Description("获取指定角色的基本信息、用户、模块、按钮权限")]
        [ReturnType(typeof(DetailData))]
        public ApiResult GetRoleDetail(int RoleID)
        {
            var dc = new SysEntities();
            var query = (from r in dc.sys_role
                         where r.IsRemove == false && r.ID == RoleID
                         select new
                         {
                             r,
                             userCount = dc.sys_user_role.Count(t => t.RoleID == r.ID),
                             DeptName = dc.sys_dept.FirstOrDefault(t => t.DeptID == r.DeptID).DeptContent
                         }).FirstOrDefault();
            if (query == null) return Error("无数据");
            var result = new DetailData
            {
                ID  =query.r.ID,
                RoleName = query.r.RoleName,
                IsEffective = query.r.IsEffective,
                RoleType = query.r.RoleType,
                Memo = query.r.Memo,    
                Sort = (int)query.r.Sort,       
                UserCount = query.userCount,
                DeptName = query.DeptName,
                RoleUserList = GetUserList(query.r.ID),
                RoleModuleList = GetMoleList(query.r.ID),
                RoleBtnList = GetBtnList(query.r.ID)
            };
            return Success(result);
        }

        [Description("获取指定角色里面的用户信息和模块信息")]
        [ReturnType(typeof(PaperData<model.UserData.ListData>))]
        public ApiResult GetUserListByRoleId(int RoleID)
        {
            var dc = new SysEntities();
            var result = new RoleUserModuleBtn();
            var query = (from b in dc.sys_button
                            join mp in dc.sys_module_privilege on b.ID equals mp.BtnID
                            join m in dc.sys_module on mp.ModuleID equals m.ID
                            join r in dc.sys_role on mp.RoleID equals r.ID
                            where r.ID == RoleID
                            select new {
                                b,
                                m.ID,
                                m.ModuleName,
                                m.Type,
                            }).ToList();
            result.userList = GetUserList(RoleID);
            result.moduleList = query.Select(r => new ModuleBtnList
            {
                ID = r.ID,
                ModuleName = r.ModuleName,
                Type = r.Type,
            }).DistinctBy(t => t.ID).ToList();
            foreach (var li in result.moduleList)
            {
                li.btnList = query.Where(r => r.ID == li.ID).Select(d => d.b).ToList().Select(r => new ModifyBtnData
                {
                    ID = r.ID,
                    BtnName = r.BtnName,
                }).ToList();
            }
            return Success(result);
        }

        /// <summary>
        /// 获取角色用户列表
        /// </summary>
        /// <param name="RoleID"></param>
        /// <returns></returns>
        public IList<UserList> GetUserList(int RoleID)
        {
            var dc = new SysEntities();
            var query = from c in dc.sys_user_role 
                        join u in dc.sys_users on c.UserID equals u.UserID
                        where c.RoleID == RoleID
                        select u;
            return (from c in query select c).ToList().Select(t => new UserList
            {
               UsersID = t.UserID,
               UserName = t.UserName,
               Sex = t.Sex
            }).ToList();
        }
        /// <summary>
        /// 获取角色模块列表
        /// </summary>
        /// <param name="RoleID"></param>
        /// <returns></returns>
        public IList<ModuleList> GetMoleList(int RoleID)
        {
            var dc = new SysEntities();
            var query = from c in dc.sys_role
                        join u in dc.sys_module_privilege on c.ID equals u.RoleID
                        join m in dc.sys_module on u.ModuleID equals m.ID
                        where c.ID == RoleID
                        select m;
            return (from c in query select c).Distinct().ToList().Select(t => new ModuleList
            {
                ModuleCode = t.ModuleCode,
                ModuleName = t.ModuleName
            }).ToList();
        }
        /// <summary>
        /// 获取角色按钮列表
        /// </summary>
        /// <param name="RoleID"></param>
        /// <returns></returns>
        public IList<ButtonList> GetBtnList(int RoleID)
        {
            var dc = new SysEntities();
            var query = from c in dc.sys_role
                        join u in dc.sys_module_privilege on c.ID equals u.RoleID
                        join m in dc.sys_button on u.BtnID equals m.ID
                        where c.ID == RoleID
                        select m;
            return (from c in query select c).Distinct().ToList().Select(t => new ButtonList
            {
                BtnName = t.BtnName
            }).ToList();
        }

        [JsonType]
        [Description("设置角色用户")]
        [ReturnType(typeof(int), "0-成功")]
        public ApiResult SetUsers([ParamDescription("角色用户列表")]model.RoleData.InitRoleData param)
        {
            var dc = new SysEntities();
            if (param == null || param.list.Count == 0) return Error("参数对象为空");
            foreach (var item in param.list)
            {
                dc.sys_user_role.Where(o => o.RoleID == item.RoleID).Delete();
                foreach (var t in item.UsersID)
                {
                    var add = new sys_user_role
                    {
                        UserID = t,
                        RoleID = item.RoleID
                    };
                    dc.sys_user_role.Add(add);
                }
            }
            try
            {
                dc.SaveChanges();
            }
            catch (Exception ex)
            {
                return Error(ex.Message);
            }
            return Success(0);
        }

        [Description("获取角色下的所有用户")]
        public ApiResult GetUsers([ParamDescription("角色ID")]int RoleID)
        {
            var dc = new SysEntities();
            var query = (from ur in dc.sys_user_role
                         join u in dc.sys_users on ur.UserID equals u.UserID
                         where ur.RoleID == RoleID
                         select new { ur.RoleID, ur.UserID, u.UserName, u.Sex });
            var result = query.OrderBy(t => t.UserID).Select(o => new model.RoleData.UserList()
            {
                UsersID = o.UserID,
                Sex = o.Sex,
                UserName = o.UserName
            }).ToList();
            return Success(result);
        }

        [JsonType]
        [Description("设置角色权限")]
        [ReturnType(typeof(int), "0-成功")]
        public ApiResult SetModules([ParamDescription("角色所拥有模块权限")]model.RoleData.InitRoleModuleData param)
        {
            if (param == null) return Error("参数对象为空");
            var dc = new SysEntities();
            var tran = dc.Database.BeginTransaction();
            dc.sys_module_privilege.Where(o => o.RoleID == param.RoleID).Delete();
            foreach (var item in param.list)
            {
                if (item.BtnID !=null && item.BtnID.Count >0)
                {
                    foreach (var t in item.BtnID)
                    {
                        var add = new sys_module_privilege
                        {
                            BtnID = t,
                            RoleID = param.RoleID,
                            ModuleID = item.ModuleID
                        };
                        dc.sys_module_privilege.Add(add);
                    }
                }
                else
                {
                    var add = new sys_module_privilege
                    {
                        BtnID = 0,
                        RoleID = param.RoleID,
                        ModuleID = item.ModuleID
                    };
                    dc.sys_module_privilege.Add(add);
                }
            }
            try
            {
                dc.SaveChanges();
                tran.Commit();
            }
            catch (Exception ex)
            {
                tran.Rollback();
                return Error(ex.Message);
            }
            return Success(0);
        }

        [Description("获取角色拥有的模块及按钮权限")]
        [ReturnType(typeof(model.RoleData.InitRoleModuleData))]
        public ApiResult GetModules([ParamDescription("角色ID")]int RoleID)
        {
            //TODO:后期加缓存
            var dc = new SysEntities();
            var result = dc.sys_module_privilege
                .Where(t => t.RoleID == RoleID)
                .GroupBy(o => o.ModuleID)
                .Select(p => new
                {
                    Id = p.Key,
                    BtnList=(from mp in dc.sys_module_privilege where mp.ModuleID==p.Key && mp.RoleID==RoleID select mp)
                });
            var list = new model.RoleData.InitRoleModuleData
            {
                RoleID = RoleID,
                list = result.Select(o => new model.RoleData.SingleRoleModuleData
                {
                    ModuleID = o.Id,
                    BtnID = o.BtnList.OrderBy(r=>r.BtnID).Select(a => a.BtnID).ToList()
                }).ToList()
            };
            return Success(list);
        }

        [Description("获取指定角色的模块下拥有的按钮权限(停用)")]
        [ReturnType(typeof(IList<int>))]
        public ApiResult GetModulesBtn([ParamDescription("角色ID")]int RoleID,
            [ParamDescription("模块ID")]int ModuleID)
        {
            return NotDoneError();
            //TODO:后期加缓存
            var dc = new SysEntities();
            var result = dc.sys_module_privilege
                .Where(t => t.RoleID == RoleID && t.ModuleID == ModuleID)
                .Select(p => new
                {
                    BtnID = p.BtnID
                }).ToList();
            return Success(result);
        }
    }
}
